package com.doeis.manage.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.doeis.common.Constant;
import com.doeis.core.SuperAction;
import com.doeis.core.bean.Msg;
import com.doeis.manage.bean.User;
import com.doeis.manage.service.UserService;
import com.doeis.tools.DateHelper;
import com.doeis.tools.HashKit;
import com.doeis.tools.StringHelper;

/**
 * 
 * @author wxy
 * @date 2014-1-6
 */
@WebServlet(urlPatterns = "/user/*")
public class UserAction extends SuperAction {

	private UserService userService = new UserService();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doRequest(String methodName, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if ("index".equals(methodName)) {
			toPage(methodName, "user", request, response);
		} else if ("login".equals(methodName)) {
			login(methodName, request, response);
		} else if ("doRegister".equals(methodName)) {
			register(methodName, request, response);
		} else if ("captcha".equals(methodName)) {
			captcha(request, response);
		} else if ("exist".equals(methodName)) {
			exist(methodName, request, response);
		} else if ("setting".equals(methodName)) {
			if (checkSession(request, response)) {
				setting(methodName, request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else if ("doSetting".equals(methodName)) {
			if (checkSession(request, response)) {
				doSetting(methodName, request, response);
			} else {
				toPage("index", "index", request, response);
			}
		} else {
			toPage(methodName, "user", request, response);
		}
	}

	private void captcha(HttpServletRequest request, HttpServletResponse response) {
		captcha(response, "randomCodeKey");
	}

	private void register(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String confirm_password = request.getParameter("confirm_password");
			String captcha = request.getParameter("v_code");
			if (StringHelper.isNull(username) || StringHelper.isNull(password)) {
				addActionMessage(request, "用户名密码不能为空");
				errorPage("error", request, response);
				return;
			}
			if (StringHelper.isNull(captcha) || !validate(request, captcha)) {
				addActionMessage(request, "验证码不正确");
				errorPage("error", request, response);
				return;
			}

			User user = userService.findByName(username);
			if (user != null) {
				addActionMessage(request, "用户已存在");
				errorPage("error", request, response);
				return;
			}
			if (!password.equals(confirm_password)) {
				addActionMessage(request, "确认密码不一致");
				errorPage("error", request, response);
				return;
			}
			user = new User();
			user.setName(username);
			user.setPassword(HashKit.md5(password));
			user.setReg_time(DateHelper.getTimestampNowDate());

			boolean result = userService.insertUser(user);
			if (result) {
				addActionMessage(request, "注册失败");
				errorPage("error", request, response);
				return;
			}
			request.getSession().setAttribute(Constant.SYSTEM_CURRENT_USER, user);
			response.sendRedirect("/index");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void login(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String captcha = request.getParameter("v_code");
			if (username == null && password == null && null == captcha) {
				toPage(methodName, "user", request, response);
				return;
			}
			if (StringHelper.isNull(username) || StringHelper.isNull(password)) {
				addActionMessage(request, "用户名密码不能为空");
				errorPage("error", request, response);
				return;
			}
			if (StringHelper.isNull(captcha) || !validate(request, captcha)) {
				addActionMessage(request, "验证码不正确");
				errorPage("error", request, response);
				return;
			}

			User user = userService.findByName(username);
			if (user == null) {
				addActionMessage(request, "用户不存在");
				errorPage("error", request, response);
				return;
			}
			if (!user.getPassword().equals(HashKit.md5(password))) {
				addActionMessage(request, "用户密码不正确");
				errorPage("error", request, response);
				return;
			}
			request.getSession().setAttribute(Constant.SYSTEM_CURRENT_USER, user);
			String userCoolkie = HashKit.md5(user.getUsername() + Math.random() * 1000);
			Cookie cookie = new Cookie("userCookie", userCoolkie);
			cookie.setMaxAge(7 * 86400);
			cookie.setPath("/");
			addCookie(response, cookie);
			user.setCookie_token(userCoolkie);
			user.setCookie_token_expire(DateHelper.addTime(7));
			userService.update(user);
			response.sendRedirect("/item/index");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void exist(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			request.getSession().setAttribute(Constant.SYSTEM_CURRENT_USER, null);
			Cookie cookie = new Cookie("userCookie", "sss");
			cookie.setMaxAge(0);
			cookie.setPath("/");
			addCookie(response, cookie);
			response.sendRedirect("/index");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setting(String methodName, HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("user", getLoginUser(request));
		toPage(methodName, "user", request, response);
	}

	public void doSetting(String methodName, HttpServletRequest request, HttpServletResponse response) {
		try {
			Msg msg = new Msg(false, "修改失败");
			String new_password = request.getParameter("new_password");
			String password = request.getParameter("password");
			User user = getLoginUser(request);
			if (!user.getPassword().equals(HashKit.md5(password))) {
				msg.setMsg("用户密码不正确");
				sendJsonObject(msg, response);
				return;
			}
			user.setPassword(HashKit.md5(new_password));

			boolean result = userService.update(user);
			if (result) {
				msg.setMsg("修改成功");
				msg.setStatus(true);
			}
			sendJsonObject(msg, response);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
